package org.playground.booking.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.playground.booking.dto.UserDto;
import org.playground.booking.entity.User;
import org.playground.booking.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Api
@RestController
@RequestMapping(path = "/api/user/*")
public class UserController {

    @Autowired
    private IUserService userService;

    @ApiOperation( value = "get the user information with openid")
    @RequestMapping(path = "/user",produces = "application/json",method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<UserDto> readUser(String openId){
        User user = userService.readUserByOpenId(openId);

        if(user!=null){
            UserDto userDto = new UserDto();
            userDto.setId(user.getId());
            userDto.setLoyalty(user.isLoyalty());
            userDto.setName(user.getName());
            userDto.setOpenId(user.getOpenId());

            return new ResponseEntity<UserDto>(userDto, HttpStatus.OK);
        }else{
            return new ResponseEntity<UserDto>(HttpStatus.NOT_FOUND);
        }
    }

    @ApiOperation( value = "get the user information with openid")
    @RequestMapping(path = "/user",produces = "application/json",method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<UserDto> createUser(String openId,boolean isLoyalty){
        User user = userService.createUser(openId,isLoyalty);
        UserDto userDto = new UserDto();
        userDto.setId(user.getId());
        userDto.setLoyalty(user.isLoyalty());
        userDto.setName(user.getName());
        userDto.setOpenId(user.getOpenId());
        return new ResponseEntity<UserDto>(userDto,HttpStatus.CREATED);
    }

    @ApiOperation(value="")
    @RequestMapping(path="/user",produces = "application/json",method = RequestMethod.PUT)
    @ResponseBody
    public ResponseEntity<String> updateUser(UserDto toUpdate){
        if(toUpdate==null){
            return new ResponseEntity<String>("{\"status\":\"fail\"}",HttpStatus.NOT_MODIFIED);
        }

        userService.updateUser(toUpdate);
        return new ResponseEntity<String>("{\"status\":\"success\"}",HttpStatus.OK);
    }
}
